import dash
from dash import html, dcc
from dash.dependencies import Input, Output
import dash_bootstrap_components as dbc
from server import server  # <--- 导入 server.py 中定义的 Flask server

from flask import Flask,session,redirect
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate

from modules.bigscreen.layouts import layout as bigscreen_layout
# 导入其他页面布局，例如登录页
from modules.login import layouts as login_layout

import base64

from modules.repair.layouts import create_repair_layout

from modules.repair.callbacks import register_repair_callbacks
from modules.maintain.layouts import maintain_layout
from modules.maintain.callbacks import register_maintain_callbacks
from modules.inspection.layouts import inspection_layout
from modules.inspection.callbacks import register_inspection_callbacks
from modules.system.layouts import change_password_layout, user_manage_layout
# from modules.repair.modals import register_modal_callbacks


# 初始化应用
dash_app = dash.Dash(
    __name__,
    server=server,
    url_base_pathname='/dash/',
    external_stylesheets=[
        '/static/css/equipment.css',
        # dbc.themes.BOOTSTRAP,
        '/static/css/bootstrap.min.css',
        # '/static/css/styles.css'  # 确保这行存在
    ],
    suppress_callback_exceptions=True
)



#  导入并注册回调函数


from modules.login.callbacks import register_callbacks as register_login_callbacks
register_login_callbacks(dash_app)
register_repair_callbacks(dash_app)

from modules.repair.callbacks2 import register_repair_respond_callbacks
register_repair_respond_callbacks(dash_app)

from modules.repair.callbacks3 import register_callbacks as register_repair_callbacks3
register_repair_callbacks3(dash_app)

from modules.repair.callbacks4 import register_repair_complete_callbacks
register_repair_complete_callbacks(dash_app)

from modules.maintain.callbacks import register_maintain_callbacks
register_maintain_callbacks(dash_app)

from modules.inspection.callbacks import register_inspection_callbacks
register_inspection_callbacks(dash_app)


from modules.bigscreen.callback import register_callbacks as register_bigscreen_callbacks
register_bigscreen_callbacks(dash_app)

from modules.bigscreen.callback2 import register_callbacks as register_bigscreen_callbacks2
register_bigscreen_callbacks2(dash_app)

from modules.system.callbacks import register_callbacks as register_system_callbacks
register_system_callbacks(dash_app)



# 注册设备台账模块的回调（只注册一次）
from modules.equipment.callbacks import register_callbacks as register_equipment_module_callbacks
register_equipment_module_callbacks(dash_app)

from modules.equipment.callbacks2 import register_callbacks as register_equipment_module_callbacks2
register_equipment_module_callbacks2(dash_app)

#页面导入

from modules.login.layouts import layout as login_layout

from modules.bigscreen.layouts import layout as bigscreen_layout



# 从新的模块导入 management_menu
from modules.system.components import management_menu



# 读取图片并转换为base64
image_path = "static/icon/leftup_logo.png"
encoded_image = ""
try:
    with open(image_path, 'rb') as f:
        encoded_image = base64.b64encode(f.read()).decode('ascii')
except Exception as e:
    print(f"无法加载图片: {str(e)}")

# 设置应用布局
dash_app.layout = html.Div([
    dcc.Location(id='url', refresh=False),
    html.Div(id='navbar-container'),  # 创建一个容器用于条件显示导航栏
    html.Div(id='page-content')
])

# 添加一个新的回调来控制导航栏的显示
from flask import session
from models import User

@dash_app.callback(
    Output('navbar-container', 'children'),
    [Input('url', 'pathname')]
)
def display_navbar(pathname):
    # 如果是登录页面，不显示导航栏
    # print(f" p108 pathname: {pathname} ")
    if pathname == '/dash/login' or pathname == '/dash/' or pathname == '/dash':
        return []
    else:
        # 判断当前页面
        def nav_style(target):
            if pathname == target:
                return {"color": "orange", "padding": "0 10px", "fontSize": "14px", "textDecoration": "none", "fontWeight": "bold"}
            else:
                return {"color": "white", "padding": "0 10px", "fontSize": "14px", "textDecoration": "none"}

        left_items = html.Div([
            html.Img(src=f"data:image/png;base64,{encoded_image}", height="50px", style={"display": "inline-block", "verticalAlign": "middle","animation": "pulse 5s infinite ease-in-out" }),
            html.Span("黄浦区卫生健康委员会", style={"fontSize": "18px", "fontWeight": "bold", "color": "#EEEEEE", "marginLeft": "8px", "verticalAlign": "middle"})
        ], style={"display": "flex", "alignItems": "center", "flex": "0 0 auto"})

        center_items = html.Div([
            html.Span("黄浦区医疗设备智慧监控云平台", style={
                "fontSize": "28px",
                "fontWeight": "bold",
                "letterSpacing": "8px",
                "textShadow": "0 0 8px #2196f3, 0 0 2px #fff",
                "textAlign": "center",
                "color": "#EEEEEE",
                "verticalAlign": "middle"
            })
        ], style={"flex": "1", "display": "flex", "justifyContent": "center", "alignItems": "center"})

        # 获取当前用户角色
        user_role = None
        user_id = session.get("user_id")
        if user_id:
            user = User.query.get(user_id)
            if user:
                user_role = user.role

        # 根据角色显示不同按钮
        if user_role == "user":
            right_items = html.Div([
                html.A("驾驶大屏", href="/dash/bigscreen", style=nav_style("/dash/bigscreen")),
                html.A("设备台账", href="/dash/equipment", style=nav_style("/dash/equipment")),
                html.A("退出登录", href="/dash/logout", style=nav_style("/dash/logout")),
                html.A("修改密码", href="/dash/change-password", style=nav_style("/dash/change-password")),
            ], style={"display": "flex", "alignItems": "center"})
        else:  # admin 或其他角色
            right_items = html.Div([
                html.A("驾驶大屏", href="/dash/bigscreen", style=nav_style("/dash/bigscreen")),
                html.A("设备台账", href="/dash/equipment", style=nav_style("/dash/equipment")),
                html.A("维修记录", href="/dash/repair", style=nav_style("/dash/repair")),
                html.A("保养记录", href="/dash/maintain", style=nav_style("/dash/maintain")),
                html.A("巡检记录", href="/dash/inspection", style=nav_style("/dash/inspection")),
                html.A("退出登录", href="/dash/logout", style=nav_style("/dash/logout")),
                html.A("修改密码", href="/dash/change-password", style=nav_style("/dash/change-password")),
                management_menu,
            ], style={"display": "flex", "alignItems": "center"})

        return dbc.Navbar(
            html.Div([
                html.Div(left_items, style={"flex": "0 0 auto", "minWidth": "260px", "zIndex": 2}),
                html.Div(center_items, style={
                    "position": "absolute",
                    "left": "50%",
                    "top": 0,
                    "transform": "translateX(-50%)",
                    "height": "100%",
                    "display": "flex",
                    "alignItems": "center",
                    "zIndex": 1
                }),
                html.Div(right_items, style={"flex": "0 0 auto", "minWidth": "400px", "marginLeft": "auto", "zIndex": 2})
            ], style={
                "position": "relative",
                "display": "flex",
                "alignItems": "center",
                "height": "90px",
                "width": "100%"
            }),
            color=None,
            dark=True,
            style={
                "height": "90px",
                "padding": "0 15px",
                "position": "relative",
                "background": "linear-gradient(90deg, #0d133d 0%, #233a7e 100%)",
                "borderBottom": "0",  # 彻底去除底部间隔
                "borderTop": "2px solid #2196f3",
                "boxShadow": "0 4px 12px rgba(33,150,243,0.2)"
            }
        )



from modules.equipment import init_equipment_module

@dash_app.callback(
    Output('page-content', 'children'),
    [Input('url', 'pathname')]
)
def display_page(pathname):
    # 判断是否已登录
    if 'user_id' not in session:
        # 允许访问登录页
        if pathname in ['/dash/login']:
            return login_layout
        else:
            # 未登录访问其他页面，强制跳转到登录页
            return login_layout
    # 已登录，正常路由
    if pathname == '/dash/' :
        pathname == '/dash/login'
    if  pathname == '/dash/login':
        return login_layout
    elif pathname == '/dash/equipment':
        return init_equipment_module(dash_app)  # 设备台账页面
    elif pathname == '/dash/repair':
         return create_repair_layout()
    elif pathname.startswith('/dash/equipment/repair/'): #扫码报修流程入口
        # print(f" p151 进入报修页面 pathname: {pathname} ")
        try:
            device_id = int(pathname.split('/')[-1])
            # print(f" p154 进入报修页面 device_id: {device_id} ")
            from modules.repair.layouts import create_repair_form_page2
            return create_repair_form_page2(device_id)
        except Exception:
            return html.Div("设备ID无效", style={'textAlign': 'center', 'marginTop': '50px'})
    elif pathname == '/dash/maintain':
        return maintain_layout([], [])
    elif pathname == '/dash/inspection':
        return inspection_layout([], [])
    elif pathname == '/dash/settings':
        return html.Div("系统设置页面 - 开发中")
    elif pathname == '/dash/bigscreen':
        return bigscreen_layout
    elif pathname == '/dash/change-password':
        return change_password_layout
    elif pathname == '/dash/user-manage':
        return user_manage_layout
    else:
        return html.Div([
            html.H1("404 - 页面不存在", className="text-center")
        ], style={'textAlign': 'center', 'marginTop': '50px'})




@server.route('/dash/logout')
def logout():
    session.clear()  # 清除所有session
    return redirect('/dash/login')

if __name__ == '__main__':
    dash_app.run(host='0.0.0.0', port=5000)